import React, { useState, useEffect } from 'react';
import { QRCode } from 'react-qrcode-logo';
import { Order } from '../types';

const Orders: React.FC = () => {
  const [orders, setOrders] = useState<Order[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);
  const [searchParams, setSearchParams] = useState({
    search: '',
    status: '',
    date: ''
  });
  // 添加弹窗状态
  const [showModal, setShowModal] = useState(false);
  const [selectedOrder, setSelectedOrder] = useState<Order | null>(null);
  // 打印相关状态
  const [showPrintOptions, setShowPrintOptions] = useState(false);
  const [showQRCode, setShowQRCode] = useState(false);
  const [isPrinterAvailable, setIsPrinterAvailable] = useState<boolean | null>(null);

  // 打印选项处理函数
  const handlePrintOptions = (order: Order) => {
    setSelectedOrder(order);
    setShowPrintOptions(true);
    // 检测打印机状态（浏览器环境限制，实际项目需后端支持）
    setIsPrinterAvailable(!!window.navigator.userAgent.includes('Chrome')); // 简单模拟
  };

  // 关闭打印选项弹窗
  const handleClosePrintOptions = () => {
    setShowPrintOptions(false);
  };

  // 打印机打印处理
  const handlePrintToPrinter = () => {
    if (!isPrinterAvailable) return;
    // 创建打印内容
    const printWindow = window.open('', '_blank');
    if (printWindow) {
      printWindow.document.write(`
        <html><head><title>订单打印</title></head>
        <body>
          <h1>订单详情</h1>
          <p>订单号: ${selectedOrder?.id}</p>
          <p>客户: ${selectedOrder?.customer}</p>
          <p>金额: ¥${selectedOrder?.amount.toFixed(2)}</p>
          <p>状态: ${selectedOrder?.status}</p>
          <p>日期: ${formatDate(selectedOrder?.date || '')}</p>
        </body></html>
      `);
      printWindow.document.close();
      printWindow.print();
printWindow.onafterprint = function() {
  printWindow.close();
};

    }
  };

  // 生成二维码内容
  const generateQRCode = () => {
    if (!selectedOrder) return '';
    // 生成微信可识别的订单详情URL
    return `http://localhost:3000/SS/orders/detail/${selectedOrder.id}`;
  };

  // 修改fetchOrders函数以支持查询参数
  const fetchOrders = async () => {
    try {
      setLoading(true);
      // 构建查询字符串
      const queryParams = new URLSearchParams();
      if (searchParams.search) queryParams.append('search', searchParams.search);
      if (searchParams.status) queryParams.append('status', searchParams.status);
      if (searchParams.date) queryParams.append('date', searchParams.date);

      const response = await fetch(`/SS/orders?${queryParams.toString()}`);
      if (!response.ok) throw new Error('Failed to fetch orders');
      const data = await response.json();
      setOrders(data);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'An error occurred');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchOrders();
  }, []);

  // 添加搜索参数变更处理
  const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setSearchParams(prev => ({ ...prev, search: e.target.value }));
  };

  const handleStatusChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    setSearchParams(prev => ({ ...prev, status: e.target.value }));
  };

  const handleDateChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setSearchParams(prev => ({ ...prev, date: e.target.value }));
  };

  const handleSearchSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    fetchOrders();
  };

  // 查看订单详情
  const handleViewOrder = (order: Order) => {
    setSelectedOrder(order);
    setShowModal(true);
  };

  // 关闭弹窗
  const handleCloseModal = () => {
    setShowModal(false);
    setSelectedOrder(null);
  };

  if (loading) return <div className="loading">加载中...  <style>{`
    @keyframes modalFadeIn {
      from { opacity: 0; transform: translateY(-20px); }
      to { opacity: 1; transform: translateY(0); }
    }
  `}</style>
</div>;
  if (error) return <div className="error">错误: {error}</div>;

  // 添加日期格式化函数
  const formatDate = (isoDate: string): string => {
    const date = new Date(isoDate);
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
  };

  return (
    <div className="page-container">
      <h1>订单管理</h1>
      <div className="actions-bar">
        <form onSubmit={handleSearchSubmit} style={{ display: 'flex', gap: '15px', alignItems: 'center' }}>
          <div className="filter-group" style={{ flex: '1' }}>
            <label>状态：</label>
            <select value={searchParams.status} onChange={handleStatusChange} style={{ width: '100%' }}>
              <option value="">全部</option>
              <option value="已完成">已完成</option>
              <option value="处理中">处理中</option>
              <option value="待付款">待付款</option>
            </select>
          </div>
          <div className="date-filter" style={{ flex: '1' }}>
            <label>日期：</label>
            <input type="date" value={searchParams.date} onChange={handleDateChange} style={{ width: '100%' }} />
          </div>
          <div className="search-box" style={{ flex: '2' }}>
            <input 
              type="text" 
              placeholder="搜索订单..."
              value={searchParams.search}
              onChange={handleSearchChange}
              style={{ width: '70%', marginRight: '5px' }}
            />
            <button type="submit" style={{ width: '25%' }}>搜索</button>
          </div>
        </form>
      </div>
      <div className="table-container">
        <table className="data-table">
          <thead>
            <tr>
              <th>订单号</th>
              <th>客户</th>
              <th>金额</th>
              <th>状态</th>
              <th>日期</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            {orders.map(order => (
              <tr key={order.id}>
                <td>{order.id}</td>
                <td>{order.customer}</td>
                <td>¥{order.amount.toFixed(2)}</td>
                <td>
                  <span className={`status-badge ${order.status === '已完成' ? 'success' : order.status === '处理中' ? 'warning' : 'info'}`}>
                    {order.status}
                  </span>
                </td>
                <td>{formatDate(order.date)}</td>
                <td>
                  <button className="btn btn-view" onClick={() => handleViewOrder(order)}>查看</button>
                  <button className="btn btn-print" onClick={() => handlePrintOptions(order)}>打印</button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {/* 订单详情弹窗 */}
      {showModal && selectedOrder && (
        <div style={{ position: 'fixed', top: 0, left: 0, right: 0, bottom: 0, background: 'rgba(0,0,0,0.5)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1000, backdropFilter: 'blur(3px)' }}>
          <div style={{ background: 'white', borderRadius: '12px', width: '500px', maxWidth: '90%', boxShadow: '0 10px 25px rgba(0,0,0,0.1)', overflow: 'hidden', animation: 'modalFadeIn 0.3s ease' }}>
            <div style={{ background: '#1890ff', color: 'white', padding: '16px 20px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <h2 style={{ margin: 0, fontSize: '18px', fontWeight: '600' }}>订单详情</h2>
              <button onClick={handleCloseModal} style={{ background: 'none', border: 'none', color: 'white', fontSize: '20px', cursor: 'pointer', transition: 'transform 0.2s', padding: '0 5px' }} onMouseOver={(e) => e.currentTarget.style.transform = 'scale(1.1)'} onMouseOut={(e) => e.currentTarget.style.transform = 'scale(1)'}>&times;</button>
            </div>
            <div style={{ padding: '20px', borderBottom: '1px solid #f0f0f0' }}>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 2fr', gap: '12px', fontSize: '14px' }}>
                <div style={{ color: '#666', textAlign: 'right', paddingRight: '15px' }}>订单号：</div>
                <div style={{ fontWeight: '500' }}>{selectedOrder.id}</div>
                <div style={{ color: '#666', textAlign: 'right', paddingRight: '15px' }}>客户：</div>
                <div>{selectedOrder.customer}</div>
                <div style={{ color: '#666', textAlign: 'right', paddingRight: '15px' }}>金额：</div>
                <div style={{ color: '#f5222d', fontWeight: '500' }}>¥{selectedOrder.amount.toFixed(2)}</div>
                <div style={{ color: '#666', textAlign: 'right', paddingRight: '15px' }}>状态：</div>
                <div><span className={`status-badge ${selectedOrder.status === '已完成' ? 'success' : selectedOrder.status === '处理中' ? 'warning' : 'info'}`} style={{ padding: '4px 8px', borderRadius: '4px', fontSize: '12px' }}>{selectedOrder.status}</span></div>
                <div style={{ color: '#666', textAlign: 'right', paddingRight: '15px' }}>日期：</div>
                <div>{formatDate(selectedOrder.date)}</div>
              </div>
            </div>
            <div style={{ padding: '15px 20px', textAlign: 'right', background: '#fafafa' }}>
              <button onClick={handleCloseModal} style={{ padding: '8px 16px', background: '#1890ff', color: 'white', border: 'none', borderRadius: '4px', cursor: 'pointer', transition: 'all 0.2s', fontSize: '14px' }} onMouseOver={(e) => e.currentTarget.style.background = '#096dd9'} onMouseOut={(e) => e.currentTarget.style.background = '#1890ff'}>关闭</button>
            </div>
          </div>
        </div>
      )}

      {/* 打印选项弹窗 */}
      {showPrintOptions && selectedOrder && (
        <div style={{ position: 'fixed', top: 0, left: 0, right: 0, bottom: 0, background: 'rgba(0,0,0,0.5)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1000, backdropFilter: 'blur(3px)' }}>
          <div style={{ background: 'white', borderRadius: '12px', width: '400px', maxWidth: '90%', boxShadow: '0 10px 25px rgba(0,0,0,0.1)', overflow: 'hidden', animation: 'modalFadeIn 0.3s ease' }}>
            <div style={{ background: '#1890ff', color: 'white', padding: '16px 20px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <h2 style={{ margin: 0, fontSize: '18px', fontWeight: '600' }}>打印选项</h2>
              <button onClick={handleClosePrintOptions} style={{ background: 'none', border: 'none', color: 'white', fontSize: '20px', cursor: 'pointer', transition: 'transform 0.2s', padding: '0 5px' }} onMouseOver={(e) => e.currentTarget.style.transform = 'scale(1.1)'} onMouseOut={(e) => e.currentTarget.style.transform = 'scale(1)'}>&times;</button>
            </div>
            <div style={{ padding: '20px', textAlign: 'center' }}>
              <h3 style={{ marginTop: 0, fontSize: '16px', color: '#333' }}>请选择打印方式</h3>
              <div style={{ display: 'flex', justifyContent: 'space-around', margin: '20px 0' }}>
                <div style={{ textAlign: 'center' }}>
                  <button onClick={() => setShowQRCode(true)} style={{ background: 'none', border: '1px solid #1890ff', color: '#1890ff', borderRadius: '4px', padding: '10px 15px', cursor: 'pointer', transition: 'all 0.2s' }} onMouseOver={(e) => {e.currentTarget.style.background = '#e6f7ff'}} onMouseOut={(e) => {e.currentTarget.style.background = 'none'}}>
                    生成二维码
                  </button>
                </div>
                <div style={{ textAlign: 'center' }}>
                  <button onClick={handlePrintToPrinter} style={{ background: 'none', border: '1px solid #1890ff', color: '#1890ff', borderRadius: '4px', padding: '10px 15px', cursor: 'pointer', transition: 'all 0.2s' }} onMouseOver={(e) => {e.currentTarget.style.background = '#e6f7ff'}} onMouseOut={(e) => {e.currentTarget.style.background = 'none'}}>
                    打印机打印
                  </button>
                  {isPrinterAvailable === false && (
                    <p style={{ color: '#ff4d4f', fontSize: '12px', marginTop: '5px' }}>没有连接打印机</p>
                  )}
                </div>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* 二维码弹窗 */}
      {showQRCode && selectedOrder && (
        <div style={{ position: 'fixed', top: 0, left: 0, right: 0, bottom: 0, background: 'rgba(0,0,0,0.5)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1000, backdropFilter: 'blur(3px)' }}>
          <div style={{ background: 'white', borderRadius: '12px', width: '300px', maxWidth: '90%', boxShadow: '0 10px 25px rgba(0,0,0,0.1)', overflow: 'hidden', animation: 'modalFadeIn 0.3s ease', padding: '20px' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '20px' }}>
              <h2 style={{ margin: 0, fontSize: '18px', fontWeight: '600', color: '#333' }}>订单二维码</h2>
              <button onClick={() => setShowQRCode(false)} style={{ background: 'none', border: 'none', fontSize: '20px', cursor: 'pointer', transition: 'transform 0.2s', padding: '0 5px' }} onMouseOver={(e) => e.currentTarget.style.transform = 'scale(1.1)'} onMouseOut={(e) => e.currentTarget.style.transform = 'scale(1)'}>&times;</button>
            </div>
            <div style={{ textAlign: 'center' }}>
              <QRCode value={generateQRCode()} size={200} />
              <p style={{ marginTop: '15px', fontSize: '14px', color: '#666' }}>订单号: {selectedOrder.id}</p>
              <p style={{ margin: '5px 0', fontSize: '14px', color: '#666' }}>客户: {selectedOrder.customer}</p>
              <p style={{ margin: '5px 0', fontSize: '14px', color: '#666' }}>金额: ¥{selectedOrder.amount.toFixed(2)}</p>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default Orders;
